package com.ridbor001.demo.servlet;

import com.alibaba.excel.EasyExcel;
import com.ridbor001.demo.bean.GradeExcelModel;
import com.ridbor001.demo.bean.RDBGrade;
import com.ridbor001.demo.service.RDBCourseService;
import com.ridbor001.demo.service.RDBGradeService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@WebServlet("/uploadGradeExcel")
public class GradeUploadServlet extends HttpServlet {
    RDBGradeService gradeService = new RDBGradeService();
RDBCourseService courseService = new RDBCourseService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (!isMultipart) {
            req.setAttribute("message", "表单不是 multipart 类型，无法上传！");
            req.getRequestDispatcher("/rDBGradeManage.jsp").forward(req, resp);
            return;
        }

        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (!item.isFormField() && "file".equals(item.getFieldName())) {
                    InputStream inputStream = item.getInputStream();
                    List<GradeExcelModel> gradeList = EasyExcel.read(inputStream)
                            .head(GradeExcelModel.class)
                            .sheet()
                            .doReadSync();

                    for (GradeExcelModel model : gradeList) {
                        Optional<RDBGrade> existing = gradeService.findGradeByStudentAndCourse(model.getStudentId(), model.getCourseId());
                        String gradeId = existing.map(RDBGrade::getGradeId).orElse(UUID.randomUUID().toString());
                        RDBGrade grade = new RDBGrade(
                                gradeId,
                                model.getStudentId(),
                                model.getCourseId(),
                                courseService.findCourseById(model.getCourseId()).getSemester(),
                                model.getDailyScore(),
                                model.getStageScore(),
                                model.getFinalScore()
                        );
                        gradeService.upsertGrade(grade);
                    }

                    req.getSession().setAttribute("uploadMessage", "成功导入 " + gradeList.size() + " 条成绩记录！");
                    resp.sendRedirect("gradeManage");
                    return;
                }
            }
        } catch (Exception e) {
            req.setAttribute("message", "上传失败：" + e.getMessage());
            req.getRequestDispatcher("/rDBGradeManage.jsp").forward(req, resp);
        }
    }
}
